<template>
    <div>
        <div v-if="main_start">请输入要查询的名字</div>
        <div v-if="main_searching">查询中。。。</div>
        <div v-if="errMessage">{{errMessage}}</div>
        <div class="row">
            <div class="card" v-for="(item,index) in users" :key="index">
                <a :href="item.user_url" target="_blank">
                    <img :src="item.avatar_url" style='width: 100px'/>
                </a>
                <p class="card-text">{{item.user_name}}</p>
            </div>
        </div>
    </div>
</template>

<script>
    import PubSub from 'pubsub-js'
    import axios from 'axios'

    export default {
        name: "Vmain",
        data () {
            return {
                main_start:true,
                main_searching:false,
                errMessage:'',
                users:null,
                /*users:[
                    {
                        user_url:'',
                        avatar_url:'',
                        user_name:'',
                    }
                ]*/
            }
        },
        mounted () {
            // search后 发ajax
            PubSub.subscribe('search',(msg,searchName) => {
                // 更新状态（请求中）
                this.main_start=false;
                this.main_searching=true;
                this.users=[];
                this.errorMsg = ''

                console.log(searchName)
                // https://api.github.com/search/users?q=aa
                axios.get(`https://api.github.com/search/users?q=${searchName}`).then((response) => {
                        // 更新状态（成功）
                        this.main_searching=false;
                        this.users = response.data.items.map(item => ({
                                user_url: item.html_url,
                                avatar_url: item.avatar_url,
                                user_name: item.login
                        }))
                    })
                    .catch((response) => {
                        // 更新状态（失败）
                        this.main_searching=false;

                        this.errMessage = '查询失败';
                    })
            })
        }
    }
</script>

<style lang="stylus" scoped>
    .card {
        float: left;
        width: 33.333%;
        padding: .75rem;
        margin-bottom: 2rem;
        border: 1px solid #efefef;
        text-align: center;
    }

    .card > img {
        margin-bottom: .75rem;
        border-radius: 100px;
    }

    .card-text {
        font-size: 85%;
    }
</style>